package com.example.app.components


import android.util.Log
import androidx.compose.foundation.layout.Column
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.runtime.*
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.tooling.preview.Preview
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import kotlinx.coroutines.coroutineScope

// 生命周期
@Composable
fun LifecycleSample() {
    var num by remember {
        mutableStateOf(0)
    }
    // LaunchedEffect只会在LifecycleSample()调用时走一遍
    // 传Unit或者true的时候说明参数永远不会变
    // 参数如果传num,那么num改变时都会走一遍
    LaunchedEffect(num) {
        Log.i("=====", "LaunchedEffect")
    }

    // 想添加生命周期必须得有LocalLifecycleOwner
    // LocalLifecycleOwner.current 获取当前
    // 创建事件监听器
    val lifecycleOwner = LocalLifecycleOwner.current
    DisposableEffect(Unit) {
        val lifecycleEventObserver = LifecycleEventObserver {
            _, event ->
            when(event) {
                Lifecycle.Event.ON_PAUSE -> {
                    // 进入后台的时候
                }
                Lifecycle.Event.ON_RESUME ->{
                    // 回到前台
                }
            }
        }
        // 添加
        lifecycleOwner.lifecycle.addObserver(lifecycleEventObserver)
        onDispose {
            // 移除监听器
            lifecycleOwner.lifecycle.removeObserver(lifecycleEventObserver)
        }
    }

    Column() {
        Text(text = "$num")
        Button(onClick = {
            // num值改变之后LifecycleSample()会重新走一遍,但是LanuchedEffect不会再次触发
            num++
        }) {

        }
        if (num == 5) {
//            到了5就会显示组件,超过5就会销毁
            SubScreen(num)
        }
    }

}

@Composable
fun SubScreen(num: Int) {

    DisposableEffect( Unit ) {
        Log.i("====", "进入生命周期")
        onDispose {
            Log.i("====", "销毁方法")
        }
    }

    Text(text = "6666")
}

@Preview
@Composable
fun SubScreenPreview() {

}

@Preview
@Composable
fun LifecycleSamplePreview() {
    LifecycleSample()
}

